//
//  DMLifecycleUtils.m
//  DualMediationSDK
//
//  生命周期管理工具类实现
//

#import "DMLifecycleUtils.h"

// 版本信息
static NSString * const kDMLifecycleManagerVersion = @"2.0.0";

// 默认超时时间（秒）
static const NSTimeInterval kDefaultStateTimeout = 30.0;
static const NSTimeInterval kDefaultEventTimeout = 5.0;
static const NSTimeInterval kBackgroundStateTimeout = 600.0; // 10分钟
static const NSTimeInterval kSuspendedStateTimeout = 3600.0; // 1小时

@implementation DMLifecycleUtils

#pragma mark - 状态检查工具

+ (BOOL)isApplicationInForeground {
    UIApplicationState state = [UIApplication sharedApplication].applicationState;
    return (state == UIApplicationStateActive || state == UIApplicationStateInactive);
}

+ (BOOL)isApplicationActive {
    return [UIApplication sharedApplication].applicationState == UIApplicationStateActive;
}

+ (BOOL)isApplicationInBackground {
    return [UIApplication sharedApplication].applicationState == UIApplicationStateBackground;
}

+ (DMLifecycleState)currentLifecycleStateFromApplication {
    UIApplication *app = [UIApplication sharedApplication];
    UIApplicationState state = app.applicationState;
    
    switch (state) {
        case UIApplicationStateActive:
            return DMLifecycleStateActive;
        case UIApplicationStateInactive:
            return DMLifecycleStateInactive;
        case UIApplicationStateBackground:
            return DMLifecycleStateBackground;
        default:
            return DMLifecycleStateUnknown;
    }
}

#pragma mark - 状态转换工具

+ (DMLifecycleEvent)suggestedEventForTransitionFrom:(DMLifecycleState)fromState to:(DMLifecycleState)toState {
    // 根据状态转换推荐合适的事件
    if (fromState == toState) {
        return DMLifecycleEventUnknown;
    }
    
    switch (toState) {
        case DMLifecycleStateActive:
            return DMLifecycleEventDidBecomeActive;
        case DMLifecycleStateInactive:
            return DMLifecycleEventWillResignActive;
        case DMLifecycleStateBackground:
            return DMLifecycleEventDidEnterBackground;
        case DMLifecycleStateForeground:
            return DMLifecycleEventWillEnterForeground;
        case DMLifecycleStateTerminating:
            return DMLifecycleEventWillTerminate;
        default:
            return DMLifecycleEventUnknown;
    }
}

+ (NSArray<NSNumber *> *)possibleTransitionsFromState:(DMLifecycleState)state {
    NSMutableArray *transitions = [NSMutableArray array];
    
    // 遍历所有可能的目标状态
    for (NSInteger targetState = DMLifecycleStateUnknown; targetState <= DMLifecycleStateTerminating; targetState++) {
        if (DMLifecycleIsValidStateTransition(state, (DMLifecycleState)targetState)) {
            [transitions addObject:@(targetState)];
        }
    }
    
    return [transitions copy];
}

+ (BOOL)isValidTransitionPath:(NSArray<NSNumber *> *)states {
    if (states.count < 2) {
        return YES; // 单个状态或空数组认为是有效的
    }
    
    for (NSUInteger i = 0; i < states.count - 1; i++) {
        DMLifecycleState fromState = (DMLifecycleState)[states[i] integerValue];
        DMLifecycleState toState = (DMLifecycleState)[states[i + 1] integerValue];
        
        if (!DMLifecycleIsValidStateTransition(fromState, toState)) {
            return NO;
        }
    }
    
    return YES;
}

#pragma mark - 调试和日志工具

+ (NSString *)detailedDescriptionForState:(DMLifecycleState)state 
                         includeTimestamp:(BOOL)includeTimestamp {
    NSString *stateDesc = DMLifecycleStateDescription(state);
    NSString *timestamp = includeTimestamp ? [self currentTimestampString] : @"";
    
    NSString *details = @"";
    switch (state) {
        case DMLifecycleStateLaunching:
            details = @"应用正在启动";
            break;
        case DMLifecycleStateInactive:
            details = @"应用非活跃状态（前台但不接收事件）";
            break;
        case DMLifecycleStateActive:
            details = @"应用活跃状态（前台且接收事件）";
            break;
        case DMLifecycleStateForeground:
            details = @"应用前台状态";
            break;
        case DMLifecycleStateBackground:
            details = @"应用后台状态";
            break;
        case DMLifecycleStateTerminating:
            details = @"应用正在终止";
            break;
        default:
            details = @"未知状态";
            break;
    }
    
    if (includeTimestamp && timestamp.length > 0) {
        return [NSString stringWithFormat:@"[%@] %@ - %@", timestamp, stateDesc, details];
    } else {
        return [NSString stringWithFormat:@"%@ - %@", stateDesc, details];
    }
}

+ (NSString *)detailedDescriptionForEvent:(DMLifecycleEvent)event 
                         includeTimestamp:(BOOL)includeTimestamp {
    NSString *eventDesc = DMLifecycleEventDescription(event);
    NSString *timestamp = includeTimestamp ? [self currentTimestampString] : @"";
    
    NSString *details = @"";
    switch (event) {
        case DMLifecycleEventDidFinishLaunching:
            details = @"应用启动完成";
            break;
        case DMLifecycleEventWillResignActive:
            details = @"应用即将失去活跃状态";
            break;
        case DMLifecycleEventDidEnterBackground:
            details = @"应用进入后台";
            break;
        case DMLifecycleEventWillEnterForeground:
            details = @"应用即将进入前台";
            break;
        case DMLifecycleEventDidBecomeActive:
            details = @"应用变为活跃状态";
            break;
        case DMLifecycleEventWillTerminate:
            details = @"应用即将终止";
            break;
        default:
            details = @"其他生命周期事件";
            break;
    }
    
    if (includeTimestamp && timestamp.length > 0) {
        return [NSString stringWithFormat:@"[%@] %@ - %@", timestamp, eventDesc, details];
    } else {
        return [NSString stringWithFormat:@"%@ - %@", eventDesc, details];
    }
}

+ (NSString *)transitionLogFromState:(DMLifecycleState)fromState 
                             toState:(DMLifecycleState)toState 
                           withEvent:(DMLifecycleEvent)event 
                            duration:(NSTimeInterval)duration {
    NSString *timestamp = [self currentTimestampString];
    NSString *fromDesc = DMLifecycleStateDescription(fromState);
    NSString *toDesc = DMLifecycleStateDescription(toState);
    NSString *eventDesc = DMLifecycleEventDescription(event);
    NSString *durationStr = [self formatTimeInterval:duration];
    
    return [NSString stringWithFormat:@"[%@] 状态转换: %@ -> %@ (事件: %@, 耗时: %@)", 
            timestamp, fromDesc, toDesc, eventDesc, durationStr];
}

#pragma mark - 性能监控工具

+ (NSTimeInterval)stateDurationFrom:(NSDate *)startTime 
                                 to:(nullable NSDate *)endTime {
    NSDate *end = endTime ?: [NSDate date];
    return [end timeIntervalSinceDate:startTime];
}

+ (NSString *)formatTimeInterval:(NSTimeInterval)interval {
    if (interval < 1.0) {
        return [NSString stringWithFormat:@"%.0fms", interval * 1000];
    } else if (interval < 60.0) {
        return [NSString stringWithFormat:@"%.2fs", interval];
    } else if (interval < 3600.0) {
        NSInteger minutes = (NSInteger)(interval / 60);
        NSInteger seconds = (NSInteger)interval % 60;
        return [NSString stringWithFormat:@"%ldm %lds", (long)minutes, (long)seconds];
    } else {
        NSInteger hours = (NSInteger)(interval / 3600);
        NSInteger minutes = (NSInteger)(interval / 60) % 60;
        return [NSString stringWithFormat:@"%ldh %ldm", (long)hours, (long)minutes];
    }
}

+ (BOOL)isAbnormalDuration:(NSTimeInterval)duration forState:(DMLifecycleState)state {
    NSTimeInterval threshold = [self defaultTimeoutForState:state];
    return duration > threshold;
}

#pragma mark - 配置和常量

+ (NSTimeInterval)defaultTimeoutForState:(DMLifecycleState)state {
    switch (state) {
        case DMLifecycleStateBackground:
            return kBackgroundStateTimeout;
        case DMLifecycleStateTerminating:
            return kDefaultStateTimeout;
        default:
            return kDefaultStateTimeout;
    }
}

+ (NSTimeInterval)defaultTimeoutForEvent:(DMLifecycleEvent)event {
    static const NSTimeInterval kLaunchEventTimeout = 30.0;
    static const NSTimeInterval kTerminateEventTimeout = 10.0;
    
    switch (event) {
        case DMLifecycleEventDidFinishLaunching:
            return kLaunchEventTimeout;
        case DMLifecycleEventWillTerminate:
            return kTerminateEventTimeout;
        default:
            return kDefaultEventTimeout;
    }
}

+ (NSString *)lifecycleManagerVersion {
    return kDMLifecycleManagerVersion;
}

#pragma mark - 私有辅助方法

+ (NSString *)currentTimestampString {
    static NSDateFormatter *formatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
    });
    
    return [formatter stringFromDate:[NSDate date]];
}

@end